const DEFAULT_PING_INTERVAL = 30000;
const DEFAULT_RECONNECT_INTERVAL = 1000;

class WebSocketClient {
	constructor(options = {}) {
		// WebSocket 连接 URL
		this.url = options.url;
		this.wsOptions = options.wsOptions;

		// 心跳间隔，默认 30s
		this.pingInterval = options.pingInterval || DEFAULT_PING_INTERVAL;

		// 重连间隔，默认 1s
		this.reconnectInterval = options.reconnectInterval || DEFAULT_RECONNECT_INTERVAL;

		// 是否自动重连，默认为 true
		this.autoReconnect = options.autoReconnect !== undefined ? options.autoReconnect : true;

		// WebSocket 对象
		this.socket = null;

		// 事件监听器
		this.listeners = {};

		// 心跳定时器
		this.pingTimer = null;

		// 重连定时器
		this.reconnectTimer = null;

		// 是否由用户手动关闭
		this.closedByUser = false;

		// 建立 WebSocket 连接
		this.connect();
	}

	connect() {
		// 使用 WebSocket 对象建立连接
		this.socket = new WebSocket(this.url, this.wsOptions);

		// 连接成功
		this.socket.onopen = (event) => {
			// console.log('WebSocket connected');
			this.emit('open', event);

			// 开始发送心跳包
			this.startHeartbeat();
		};

		// 收到消息
		this.socket.onmessage = (event) => {
			// console.log('WebSocket message received:', event.data);
			this.emit('message', event);

			// 重置心跳包定时器
			this.resetHeartbeat();
		};

		// 发生错误
		this.socket.onerror = (event) => {
			console.error('WebSocket error:', event);
			this.emit('error', event);

			// 重置心跳包定时器并尝试重连
			this.resetHeartbeat();
			if (this.socket.readyState === WebSocket.OPEN) {
				this.reconnect();
			}
		};

		// 连接关闭
		this.socket.onclose = (event) => {
			// console.log('WebSocket closed');
			this.emit('close', event);
			this.reconnect()
		};
		// 重置心
		this.resetHeartbeat();
		// if (!this.closedByUser && this.autoReconnect) {
		// 	this.reconnect();
		// }
	}
	/**
 * 发送数据
 * @param {*} data 要发送的数据
 */
	send(data) {
		if (this.socket && this.socket.readyState === WebSocket.OPEN) {
			this.socket.send(data);
		} else {
			console.error('WebSocket is not open');
		}
	}

	/**
	 * 添加事件监听器
	 * @param {*} event 事件类型
	 * @param {*} listener 监听器
	 */
	on(event, listener) {
		if (!this.listeners[event]) {
			this.listeners[event] = [];
		}
		this.listeners[event].push(listener);
	}

	/**
	 * 触发事件监听器
	 * @param {*} event 事件类型
	 * @param {*} data 事件数据
	 */
	emit(event, data) {
		const listeners = this.listeners[event];
		if (listeners) {
			listeners.forEach((listener) => listener(data));
		}
	}

	/**
	 * 手动关闭连接
	 */
	close() {
		this.closedByUser = true;
		if (this.socket) {
			this.socket.close();
			this.stopHeartbeat();
		}
	}

	/**
	 * 开始发送心跳包
	 */
	startHeartbeat() {
		if (this.pingInterval > 0) {
			this.pingTimer = setInterval(() => {
				if (this.socket.readyState === WebSocket.OPEN) {
					this.socket.send('ping');
				}
			}, this.pingInterval);
		}
	}

	/**
	 * 停止发送心跳包
	 */
	stopHeartbeat() {
		clearInterval(this.pingTimer);
	}

	/**
	 * 重置心跳包定时器
	 */
	resetHeartbeat() {
		this.stopHeartbeat();
		this.startHeartbeat();
	}

	/**
	 * 尝试重连
	 */
	reconnect() {
		if (this.reconnectInterval > 0 && !this.reconnectTimer) {
			this.reconnectTimer = setTimeout(() => {
				this.reconnectTimer = null;
				// console.log('WebSocket reconnecting...');
				this.connect();
			}, this.reconnectInterval);
		}
	}
}

/**

创建 WebSocket 实例
@param {*} url WebSocket 连接 URL
@param {*} options 选项参数，包括 wsOptions(ws选项) autoReconnect（是否自动重连）、pingInterval（心跳间隔）、reconnectInterval（重连间隔）
@returns WebSocketClient 实例
*/
export default function createWebSocket(url, options = {}) {
	const { wsOptions, autoReconnect, pingInterval, reconnectInterval } = options;
	return new WebSocketClient({
		url,
		wsOptions,
		pingInterval: typeof pingInterval === 'number' ? pingInterval : DEFAULT_PING_INTERVAL,
		reconnectInterval: typeof reconnectInterval === 'number' ? reconnectInterval : DEFAULT_RECONNECT_INTERVAL,
		autoReconnect: autoReconnect !== undefined ? autoReconnect : true,
	});
}
